import 'package:flutter_jd/api/blog_api.dart';
import 'package:flutter_jd/models/blog_model.dart';
import 'package:get/get_state_manager/get_state_manager.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:get/get.dart';

class BlogController extends GetxController {
  final blogList = RxList<BlogModel?>([]);
  int currentPage = 1;
  int lastPage = 1;
  RefreshController refreshController = RefreshController(
    initialRefresh: false,
  );

  @override
  void onInit() {
    super.onInit();
    loadData();
  }

  @override
  void onClose() {
    super.onClose();
  }

  // 加载数据
  void loadData({bool loadMore = false}) async {
    if (loadMore) {
      ++currentPage;
    }
    BlogApi.getBlogList(currentPage).then((res) {
      List<BlogModel> list = [];

      for (var blog in res['data']) {
        blogList.add(BlogModel.fromJson(blog));
      }

      lastPage = res['lastPage'];
      blogList.addAll(list);
      update();

      refreshController.loadComplete();
    });
  }

  // 下拉刷新
  onRefresh() async {
    // refreshController.loadComplete();
    loadData();

    await Future.delayed(Duration(milliseconds: 600));
    refreshController.refreshCompleted();
  }

  // 加载更多
  onLoading() async {
    await Future.delayed(Duration(milliseconds: 200));

    // 加载更多数据
    if (currentPage < lastPage) {
      loadData(loadMore: true);
    } else if (currentPage == lastPage) {
      refreshController.loadNoData();
    }
  }
}
